import cv2 as cv

video_path = r'C:\Users\Administrator\Desktop\python\AI\material\vtest.avi'


cap = cv.VideoCapture(video_path)

#计算第一帧特征点
ret, prev = cap.read()
#创建一个提取背景的算子
fgbg = cv.createBackgroundSubtractorMOG2()
thresh = 200



while True:
     ret,frame = cap.read()
     if not ret:
          break

     #提取背景
     fgmask = fgbg.apply(frame)

     #对背景二值化
     _,fgmask = cv.threshold(fgmask, 30,0xff,cv.THRESH_BINARY)

     #获取原图中的背景
     bgImage = fgbg.getBackgroundImage()

     

     image,cnts,_ = cv.findContours(fgmask.copy(),cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)

     count = 0
     rect = []
     for c in cnts:
          area = cv.contourArea(c)
          if area<thresh:
               continue
          count+=1
          x,y,w,h = cv.boundingRect(c)
          rect.append((x,y,w,h))
          cv.rectangle(frame,(x,y),(x+w,y+h),(0,0,0xff),2)
          
     
     print('共监测到',count,'个目标:','\n')
     print('    x        y        width        height   ')
     for i in rect:
          print('   %d      %d         %d           %d   ' %(x,y,w,h))
     print('')
     cv.imshow('frame',frame)
     cv.imshow('FontImage',fgmask)
     cv.imshow('Background',bgImage)

     key = cv.waitKey(30)
     if key==27:
          break



cap.release()

        
